﻿using System.Collections.Generic;
using System.Linq;
using DataScripter.Containers;
using DataScripter.Database;
using DataScripter.Database.SqlServer;
using DataScripter.Scripting.InputSources;
using DataScripter.Scripting.Processes.Output;

namespace DataScripter.Scripting.Processes
{
	class TruncateSqlServerTableProcessToFile : BaseProcess
	{
		private ISqlServerInputSource InputSource { get; set; }
		private ITableList TableList { get; set; }

		public TruncateSqlServerTableProcessToFile(string name, IContainer container) 
			: base(name, container)
		{
		}

		public override void Initialize(Dictionary<string, string> parameters)
		{
			InputSource = GetTypedParameter<ISqlServerInputSource>(parameters, "SqlServerInputSource");
			TableList = GetTypedParameter<ITableList>(parameters, "TableList");
		}

		public override IProcessOutput Run()
		{
			IDatabaseStructure databaseStructure = Container.Resolve<IDatabaseStructure>();

			IList<ITableStructure> tables = TableList.Select(databaseStructure.GetTable).ToList();

			IList<IForeignKey> foreignKeysToBeDropped = (from table in tables
			                                             from foreignKey in table.ForeignKeys
			                                             let key = foreignKey
			                                             where tables.Any(t => t.TableName == key.ReferencedTableName)
			                                             select foreignKey).ToList();

			ISqlServerStatementCreator statementCreator = InputSource.StatementCreator;
			foreach (IForeignKey foreignKey in foreignKeysToBeDropped)
			{
				string dropStatement = statementCreator.DropForeignKey(foreignKey);
				string createStatement = statementCreator.CreateForeignKey(foreignKey);
			}
			foreach (ITableStructure table in tables)
			{
				string truncateTableStatement = statementCreator.TruncateTable(table);
			}

			// execute statements in transaction
			// SET XACT_ABORT ON
			// BEGIN TRAN
			// execute all drop foreign key statements
			// execute all truncate table statements
			// execute all create foreign key statements
			// ROLLBACK

			// TEST the script first before running in production mode !! ;-)
			return null;
		}

	}
}
